package org.javaboy.pub_sub_demo.config;

import org.javaboy.pub_sub_demo.consumer.MyConsumer01;
import org.javaboy.pub_sub_demo.consumer.MyConsumer02;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    public static final String CHANNEL_01 = "channel_01";
    public static final String CHANNEL_02 = "channel_02";

    /**
     * 因为 MyConsumer02 没有实现 MessageListener 接口，所以这里需要使用 MessageListenerAdapter 来适配
     *
     * @return
     */
    @Bean
    MessageListenerAdapter messageListenerAdapter(MyConsumer02 myConsumer02) {
        MessageListenerAdapter receiveMessage = new MessageListenerAdapter(myConsumer02, "receiveMessage");
        //将来收到消息之后，会通过这里设置的序列化方案进行反序列化
        receiveMessage.setSerializer(new GenericJackson2JsonRedisSerializer());
        return receiveMessage;
    }

    @Bean
    RedisMessageListenerContainer container(MyConsumer01 consumer01, MessageListenerAdapter messageListenerAdapter, RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(consumer01, new PatternTopic(CHANNEL_01));
        container.addMessageListener(messageListenerAdapter, new PatternTopic(CHANNEL_02));
        return container;
    }

    @Bean
    RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(connectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return redisTemplate;
    }
}
